package com.tanhua.admin.listener;

import com.tanhua.autoconfig.template.AliyunGreenTemplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class AuditListener {

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private AliyunGreenTemplate template;

    @RabbitListener(bindings =
    @QueueBinding(value =
    @Queue(value = "tanhua.audit.queue", durable = "true"),
            exchange = @Exchange(value = "tanhua.audit.exchange", type = ExchangeTypes.TOPIC),
            key = "audit.movement"
        )
    )
    public void audit(String movementId) {
        System.out.println("内容审核：id="+movementId);
        //1.根据id查询动态
        try {
            Movement movement = movementApi.findById(movementId);
            if (movement != null && movement.getState() == 0) {
                //2.审核文本图片
                Map<String, String> textScan = template.greenTextScan(movement.getTextContent());
                Map<String, String> imageScan = template.imageScan(movement.getMedias());
                //3.判断结果
                int state = 0;
                if (textScan != null && imageScan != null) {
                    String text = textScan.get("suggestion");
                    String image = imageScan.get("suggestion");
                    if("block".equals(text) || "block".equals(image) ) {
                        //驳回
                        state = 2;
                    }else if("pass".equals(text) && "pass".equals(image)) {
                        //通过
                        state = 1;
                    }
                }
                //4.修改动态
                movementApi.update(movementId, state);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
